package com.txt.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.txt.annotion.Update;
import com.txt.properties.CosProperties;
import com.txt.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;


@Service
@Update(value = "cos")
public class COSUploadServiceImpl implements UploadService {
    @Autowired
    private COSClient cosClient;
    @Autowired
    private CosProperties cosProperties;

    @Override
    public String upload(MultipartFile file, String key) throws IOException {
        // 添加默认路径
        key = cosProperties.getDefaultPath() + key;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(file.getContentType());
        InputStream inputStream = file.getInputStream();
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosProperties.getBucketName(),
                key, inputStream, objectMetadata);
        try {
            cosClient.putObject(putObjectRequest);
            return cosProperties.getUrl() + "/" + key;
        } catch (CosServiceException e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败：服务端错误", e);
        } catch (CosClientException e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败：客户端错误", e);
        }
    }
}
